<script setup>

  import IconSpan from '@/components/IconSpan.vue'
  import Icon from '@/components/Icon.vue'
  import Button from '@/components/Button.vue'
  import { computed, ref, watch } from 'vue'
  import { uniqueId } from '@/helpers/utils'

  const props = defineProps({
    title: { required: true, type: String },
    initialCollapsedState: { type: Boolean, default: false },
    initialFilters: { type: Object, default: {} },
  })
  const collapsedState = ref(props.initialCollapsedState)

  const panelDomId = uniqueId('accordionPanel')
  const titleDomId = uniqueId('accordionTitle')

  const toggleCollapse = () => collapsedState.value = !collapsedState.value

  const actionTitle = computed(() =>
    collapsedState.value ? 'Afficher les champs de recherche' : 'Masquer les champs de recherche'
  )

  const emits = defineEmits(['applyFilters'])
  // Filters will have one key per filter set
  const filters = Object.assign({ }, props.initialFilters)

  // The change event are emited by childs of the form (eg: <input>)
  const setFilter = (e) => filters[e.target.name] = e.target.value

  const applyFilters = (e) => {
    e.preventDefault();
    emits("applyFilters", filters);
  }
  watch(
    () => props.initialFilters,
    () => Object.assign(filters, props.initialFilters),
  )

</script>

<template>

  <div class='collapsible search_filters expanded'>
    <h2 class='collapse_title'>
      <a href='#'
         :id='titleDomId'
         :aria-expanded='! collapsedState'
         accesskey='R'
         :title='actionTitle'
         :aria-label='actionTitle'
         @click='toggleCollapse'
      >
        <IconSpan name='search' alt="" />
        {{ title }}
        <Icon class='arrow' name='chevron-down' />

      </a>
    </h2>
    <div class='collapse_content'
         :id='panelDomId'
         :aria-labelledby='titleDomId'
         :hidden='collapsedState'>
      <div>
        <form id='search_form' class='form-search form-inline'
              @change='setFilter'
              @submit='applyFilters'
        >
          <slot></slot>
          <div>
            <Button css='btn-primary' icon='search' buttonType='submit'
                    title='Lancer la recherche avec ces critères'
                    label='Lancer la recherche avec ces critères'
            />
          </div>
        </form>
      </div>
    </div>
  </div>


</template>
